var currentpage = 1, totalpage = 1, pagesize = 10;//当前页、总页数
$(function () {
	if (LessonID) {
		getsetcoursecrtct();
		callfetsetcoursefun("#cs_waitrecruit");
	}
});
//切换标签时查询课程
$('#stuListTab a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
	//防太过频繁切换标签，发送过多请求
	if (previouspage.nowtime && (Date.now() - previouspage.nowtime < 2000)) {
		if ($(e.target.hash).find("tr").length) {
			$("#partpagenavbar").show();
			return;
		} else if ($(e.target.hash).find("br").length) {
			$("#partpagenavbar").hide();
			return;
		}
	}
	previouspage.nowtime = Date.now();
	$('#container img[alt="loading"]').fadeIn(100);
	currentpage = 1;
	var divid = e.target.getAttribute("href");
	callfetsetcoursefun(divid);
});
//设置课程内容
function getsetcoursecrtct() {
	$.ajax({
		url: "publishlessons/" + LessonID + "/" + Phase + "/lessoninfo",
		type: "GET",
		contentType: "application/json",
		success: function (data) {
			$("#courseAvatar").attr("src", data.image);//封面
			$("#courseAvatar").height($("#courseAvatar").width() / 1.8);
			var lang = /zh/.test(getCurrentLang());
			var str = '<span class="tag lessontypetag">' + (lang ? data.typenamecn : data.typenameen) + '</span> ';
			str += data.phase && data.phase != 1 ? (' <span class="tag lessonpstag">' + langThis("cm_coursePhase").replace("{p}", data.phase) + '</span> ') : '';
			str += ' <span class="tag lessonenddate">' + langThis("rm_csEndTime") + ' : ' + data.enddate + '</span></div><br>' + data.description;
			$("#courseIntro").html("<h4>" + data.lessonname + "</h4>" + str);//描述
			$("#courseIntro").css("max-height", $("#courseAvatar").height() + "px");
			//按钮
		},
		error: function (event) {
			layer.msg(langThis("role_optionfaild"), { icon: 2 });
			$('#container img[alt="loading"]').fadeOut();
		}
	});
}
function callfetsetcoursefun(divid) {
	$('#container img[alt="loading"]').fadeIn(100);
	var query = function (type) {
		$.ajax({
			url: "publishlessons/" + LessonID + "/" + Phase + "/studentlist/queryresult",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({
				modeid: type,
				pageindex: currentpage
			}),
			dataType: "json",
			success: function (data) {
				currentpage = data.currentPageNo;
				totalpage = data.totalPageCount;
				pagesize = data.pagesize;
				fillStuTable(data.result, divid);
			},
			error: function (event) {
				layer.msg(langThis("role_optionfaild"), { icon: 2 });
				$('#container img[alt="loading"]').fadeOut();
				// console.log(event);
			}
		});
	};
	switch (divid) {
		//待审核学生
		case "#cs_waitrecruit": query(1); break;
		//已审核学生
		case "#cs_alreadyrecruit": query(2); break;
	}
}
// 填充表格
function fillStuTable(data, divid) {
	// 填充表格
	if (!data || !data.length) {
		switch (divid) {
			case "#cs_waitrecruit": {
				$("#waitRecruit_tbd").html("<tr><td colspan='6'><br>" + langThis("rc_nostudengts")+"</td></tr>");
			} break;
			case "#cs_alreadyrecruit": {
				$("#alreadyRecruit_tbd").html("<tr><td colspan='5'><br>" + langThis("rc_nostudengtsA")+"</td></tr>");
			} break;
		}
		$('#container img[alt="loading"],#partpagenavbar').fadeOut();
		return;
	}
	var stuStr = "";
	for (var i in data) {
		stuStr += '<tr data-toggle="modal" data-stuid="' + data[i].userinfoid + '" data-target="#studentDetail" photo="' + data[i].studentphoto + '">';
		stuStr += '<td>' + data[i].studentname + '</td>';
		switch (data[i].studentsex.toString()) {
			case "1": stuStr += '<td>' + langThis("ms_male") + '</td>'; break;
			case "2": stuStr += '<td>' + langThis("ms_female") + '</td>'; break;
			default: stuStr += '<td>' + langThis("ms_malefemale") + '</td>'; break;
		}
		stuStr += '<td>' + data[i].studentuniversity + '</td>';
		stuStr += '<td>' + data[i].studentmajor + '</td>';
		switch (divid) {
			case "#cs_waitrecruit": {
				stuStr += '<td>' + (!data[i].message ? "-" : data[i].message) + '</td>';
				stuStr += '<td><a class="btn btn-link access">' + langThis("rt_accessstu") + '</a>/<a class="btn btn-link refuse">' + langThis("rt_resusestu") + '</a></td>';
			} break;
			case "#cs_alreadyrecruit": {
				stuStr += '<td><a class="btn btn-link fire">' + langThis("rt_firestu") + '</a></td>';
			} break;
		}
	}
	//绑定按钮事件
	switch (divid) {
		//待审核学生
		case "#cs_waitrecruit": {
			$("#waitRecruit_tbd").html(stuStr);
			$('div[role="tabpanel"] td>a.access').click(function (e) {
				e.stopImmediatePropagation();
				var stuid = e.target.parentElement.parentElement.getAttribute("data-stuid");
				accessStu(stuid, e.target.parentElement.parentElement);
			});
			$('div[role="tabpanel"] td>a.refuse').click(function (e) {
				e.stopImmediatePropagation();
				var stuid = e.target.parentElement.parentElement.getAttribute("data-stuid");
				refuseStu(stuid, e.target.parentElement.parentElement);
			});
		} break;
		//已审核学生
		case "#cs_alreadyrecruit": {
			$("#alreadyRecruit_tbd").html(stuStr);
			$('div[role="tabpanel"] td>a.fire').click(function (e) {
				e.stopImmediatePropagation();
				var stuid = e.target.parentElement.parentElement.getAttribute("data-stuid");
				fireStu(stuid, e.target.parentElement.parentElement);
			});
		} break;
	}
	$('#container img[alt="loading"]').fadeOut();
	$("#partpagenavbar").fadeIn();
	setpartpagebar(divid);
}
//详细信息模态框
$('#studentDetail').on('show.bs.modal', function (e) {
	var thisTR = e.relatedTarget;
	var stuid = parseInt(thisTR.getAttribute("data-stuid"));
	var modal = $("#studentDetail");
	$("#stuinfotitle").text(langThis("rc_stuDetail") + " - " + thisTR.childNodes[0].innerText);
	$("#modalstunNm").text(thisTR.childNodes[0].innerText);
	$("#modalStuScl").text(thisTR.childNodes[2].innerText);
	$("#modalStuSex").text(thisTR.childNodes[1].innerText);
	$("#modalstuMajor").text(thisTR.childNodes[3].innerText);
	$("#modelstuCmt").text(thisTR.childNodes[4].innerText);
	//头像
	var photourl = thisTR.getAttribute("photo");
	if (!/http/.test(photourl) && !/\/photos/.test(photourl)) {
		photourl = "./photos/" + photourl;
	}
	$("#modalstuimg").attr("src", photourl);
	$("#modalstuimg").height($("#modalstuimg").width());
	var bts = "";
	if (thisTR.parentElement.getAttribute("id") == "waitRecruit_tbd") {//待审核
		bts += '<button class="btn btn-success accessstu">' + langThis("rt_accessstu") + '</button>';
		bts += '<button class="btn btn-danger resusestu">' + langThis("rt_resusestu") + '</button>';
		bts += '<button class="btn btn-default" data-dismiss="modal">' + langThis("pm_cancle") + '</button>';
	} else {
		$("#modelstuCmt").parents("tr").hide();
		bts += '<button class="btn btn-danger firestu">' + langThis("rt_firestu") + '</button>';
		bts += '<button class="btn btn-default" data-dismiss="modal">' + langThis("pm_cancle") + '</button>';
	}
	modal.find("div.modal-footer").html(bts);
	modal.find("div.modal-footer>button.accessstu").click(function () {//通过
		accessStu(stuid, thisTR);
		modal.modal('hide');
	});
	modal.find("div.modal-footer>button.resusestu").click(function () {//拒绝
		refuseStu(stuid, thisTR);
		modal.modal('hide');
	});
	modal.find("div.modal-footer>button.firestu").click(function () {//开除
		fireStu(stuid, thisTR);
		modal.modal('hide');
	});
})
//确认框
function layermsg(title, msg, btn1, btn2, fun1, fun2) {
	layer.confirm(msg, {
		btn: [btn1, btn2]
	}, fun1, fun2);
	// 标题
	var header = $("div.layui-layer.layui-layer-dialog.layer-anim>div.layui-layer-title");
	if (typeof (title) == "string") {
		header.html(title);
		return;
	}
	header.html(title.text);
	header.css(title.css);
}
//招人
function accessStu(stuid, e) {
	//服务
	$.ajax({
		url: "publishlessons/" + LessonID + "/" + Phase + "/studentlist/students/" + stuid,
		type: "PUT",
		contentType: "application/json",
		data: JSON.stringify({
			modeid: 2
		}),
		dataType: "json",
		success: function () {
			e.remove();
		},
		error: function (event) {
			layer.closeAll();
			layer.msg(langThis("role_optionfaild"), { icon: 2 });
			$('#container>img[alt="loading"]').fadeOut();
		}
	});
}
//拒绝
function refuseStu(stuid, e) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-exclamation-sign'></span>&nbsp;" + langThis("rt_resusestu");
	title.css = {
		'color': "#fff",
		'background-color': '#d9534f',
		'font-weight': 'bold'
	};
	var msg = langThis("rt_resusestu_tip");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = function () {
		//服务
		$.ajax({
			url: "publishlessons/" + LessonID + "/" + Phase + "/studentlist/students/" + stuid,
			type: "DELETE",
			contentType: "application/json",
			success: function () {
				e.remove();
				layer.closeAll();
			},
			error: function (event) {
				layer.closeAll();
				layer.msg(langThis("role_optionfaild"), { icon: 2 });
				// console.log(event);
			}
		});
	};
	layermsg(title, msg, btn1, btn2, fun1);
}
//踢人
function fireStu(stuid, e) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-exclamation-sign'></span>&nbsp;" + langThis("rt_firestu");
	title.css = {
		'color': "#fff",
		'background-color': '#d9534f',
		'font-weight': 'bold'
	};
	var msg = langThis("rt_firestu_tip");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = function () {
		//服务
		$.ajax({
			url: "publishlessons/" + LessonID + "/" + Phase + "/studentlist/students/" + stuid,
			type: "DELETE",
			contentType: "application/json",
			success: function () {
				e.remove();
				layer.closeAll();
			},
			error: function (event) {
				layer.closeAll();
				layer.msg(langThis("role_optionfaild"), { icon: 2 });
				// console.log(event);
			}
		});
	};
	layermsg(title, msg, btn1, btn2, fun1);
}
//分页控制
function setpartpagebar(divid) {
	var pagesli = '';
	//首页、上一页
	if (currentpage == 1 || totalpage == 1) {
		pagesli += '<li title="' + langThis("nav_master") + '" class="active"><a>&laquo;</a></li>';
		pagesli += '<li title="' + langThis("nav_pre") + '" class="active"><a>&lt;</a></li>';
	} else {
		pagesli += '<li title="' + langThis("nav_master") + '"><a style="cursor:pointer;" onclick="gotofirstpage(\'' + divid + '\')">&laquo;</a></li>';
		pagesli += '<li title="' + langThis("nav_pre") + '"><a style="cursor:pointer;" onclick="previouspage(\'' + divid + '\')">&lt;</a></li>';
	}
	//页码
	var startpage;
	if (currentpage - 5 <= 0) {
		startpage = 1;
	} else if (currentpage + 5 > totalpage) {
		startpage = totalpage - 9;
	} else {
		startpage = currentpage - 4;
	}
	// 左过长
	if (startpage > 1) {
		pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + (startpage - 1) + ')">...</a></li>';
	} else {
		startpage = 1;
	}
	for (var j = startpage; j <= totalpage; j++) {
		if (j == currentpage) {
			pagesli += '<li class="active"><a>' + j + '</a></li>';
		} else {
			pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + j + ')">' + j + '</a></li>';
		}
		//右过长
		if ((j == startpage + 9) && (j < totalpage)) {
			pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + (startpage + 10) + ')">...</a></li>';
			break;
		}
	}
	//下一页、尾页
	if (currentpage == totalpage || totalpage == 1) {
		pagesli += '<li title="' + langThis("nav_next") + '" class="active"><a>&gt;</a></li>';
		pagesli += '<li title="' + langThis("nav_last") + '" class="active"><a>&raquo;</a></li>';
	} else {
		pagesli += '<li title="' + langThis("nav_next") + '"><a style="cursor:pointer;" onclick="nextpage(\'' + divid + '\')">&gt;</a></li>';
		pagesli += '<li title="' + langThis("nav_last") + '"><a style="cursor:pointer;" onclick="gotolastpage(\'' + divid + '\')">&raquo;</a></li>';
	}
	$("#partpagenavbar>ul.pagination").html(pagesli);
	$("#partpagenavbar").fadeIn();
}
function previouspage(divid) {
	currentpage--;
	callfetsetcoursefun(divid);
}
function nextpage(divid) {
	currentpage++;
	callfetsetcoursefun(divid);
}
function gotopage(divid, pagenum) {
	currentpage = pagenum;
	callfetsetcoursefun(divid);
}
function gotofirstpage(divid) {
	currentpage = 1;
	callfetsetcoursefun(divid);
}
function gotolastpage(divid) {
	currentpage = totalpage;
	callfetsetcoursefun(divid);
}
// 翻页快捷键
document.onkeydown = function (e) {
	var divid = $("#stuListTab>li.active>a").attr("href");
	if ((e || event).keyCode == 37 && currentpage > 1) {//上一页
		previouspage(divid);
	} else if ((e || event).keyCode == 39 && currentpage < totalpage) {//下一页
		nextpage(divid);
	} else if ((e || event).keyCode == 36 && currentpage != 1) {//首页
		gotofirstpage(divid);
	} else if ((e || event).keyCode == 35 && currentpage != totalpage) {//尾页
		gotolastpage(divid);
	}
};